package com.ry.service.impl;

import com.ry.service.FileUploadService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;

/**
 * @author ry
 * @since 2021-11-11 09:30
 **/
@Service
public class FileUploadServiceImpl implements FileUploadService {
    @Value("${upload.uploadPath}")
    private String uploadPath;

    @Value("${upload.hostname}")
    private String hostname;

    private String resourceHandler;

    @Value("${upload.resourceHandler}")
    public void setResourceHandler(String resourceHandler){
        //去掉后面那两个**
        String result = resourceHandler.substring(0,resourceHandler.length() - 2);
        this.resourceHandler = result;
    }

    @Override
    public String uploadImage(MultipartFile image) {
        File path = new File(uploadPath);
        if (!path.exists()){
            path.mkdirs();
        }
        //文件的名字
        String fileName = System.currentTimeMillis() + image.getOriginalFilename();
        //dest是本地保存的文件名字
        File dest = new File(path + File.separator + fileName);
        try {
            image.transferTo(dest);

            //目标资源url，返回给小程序
            String reStr = hostname + resourceHandler + fileName;

            return reStr;
        } catch (IOException e) {
            e.printStackTrace();
        }


        throw new RuntimeException("服务器出错，图片上传失败");
    }
}
